/*
 * ******************************************************************************
 *   Copyright © 2013-2014 sean.yanghy. All rights reserved.
 *
 *  *****************************************************************************
 */

package com.exteam.common.util;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.app.ActivityManager.RunningTaskInfo;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.StatFs;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.PopupWindow;
import android.widget.Toast;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Method;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;


/**
 * tools
 *
 * @author sean.yanghy
 * @version v1.0
 * @created 2014-07-06 13:56:23
 */
public class CommUtils {

    private static Context context;
    private static TelephonyManager tm;
    private static long lastClickTime;
    public static int screenWidth;
    public static int screenHeight;
    public static File cacheDir;

    private CommUtils() {
    }

    private CommUtils(Context ctx) {
        context = ctx;
        initScreen();
    }

    public static File getCacheDir() {
        return cacheDir;
    }

    public static Context getContext() {
        return context;
    }

    public static void initScreen() {
        DisplayMetrics dm = context.getResources().getDisplayMetrics();
        screenWidth = dm.widthPixels;
        screenHeight = dm.heightPixels;

    }

    public static void initUitls(Context ctx) {
        context = ctx;
        initScreen();
        tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        s = PreferenceManager.getDefaultSharedPreferences(context);
        e = s.edit();
        // 应用程序目录
        if (FileUtils.isExistExternalStore()) {
            cacheDir = ctx.getExternalCacheDir();
        } else {
            cacheDir = ctx.getCacheDir();
        }

    }

    public static String getDeviceId() {
        return tm.getDeviceId();
    }


    public static long toLongTime(String strDate, String format) {
        SimpleDateFormat df4 = new SimpleDateFormat(format, Locale.CHINA);
        Date d = new Date();
        try {
            d = df4.parse(strDate);
            System.out.println(d.toLocaleString());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return d.getTime();
    }

    public static void setPopupWindowTouchModal(PopupWindow popupWindow, boolean touchModal) {
        if (null == popupWindow) {
            return;
        }
        Method method;
        try {

            method = PopupWindow.class.getDeclaredMethod("setTouchModal",
                    boolean.class);
            method.setAccessible(true);
            method.invoke(popupWindow, touchModal);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public static String formatDate(long date_str, String format) {
        Date date = new Date(date_str);
        SimpleDateFormat formatter = new SimpleDateFormat(format, Locale.CHINA);
        return formatter.format(date);
    }

    public static boolean areSameDay(Date dateA, Date dateB) {
        Calendar calDateA = Calendar.getInstance();
        calDateA.setTime(dateA);

        Calendar calDateB = Calendar.getInstance();
        calDateB.setTime(dateB);

        return calDateA.get(Calendar.YEAR) == calDateB.get(Calendar.YEAR)
                && calDateA.get(Calendar.MONTH) == calDateB.get(Calendar.MONTH)
                && calDateA.get(Calendar.DAY_OF_MONTH) == calDateB.get(Calendar.DAY_OF_MONTH);
    }

    /**
     * 通过url 获得对应的Drawable资源
     *
     * @param flag 是否压缩标记
     * @param url  图片地址
     * @return
     */
    public static Bitmap getBitmapFromUrl(int flag, String url) {
        try {
            URLConnection urlc = new URL(url).openConnection();
            URLConnection urlc2 = new URL(url).openConnection();
            if (flag == 0) {
                /*
                 * return Drawable .createFromStream(urlc.getInputStream(),
				 * "image");
				 */
                return decodeSampledBitmapFromStream(
                        urlc.getInputStream(), urlc2.getInputStream(), 50, 50);
            } else if (flag == 1) {
                return
                        decodeSampledBitmapFromStream(urlc.getInputStream(),
                                urlc2.getInputStream(), 150, 150);

            } else if (flag == 2) {
                return
                        decodeSampledBitmapFromStream(urlc.getInputStream(),
                                urlc2.getInputStream(), 300, 300);
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static Bitmap decodeSampledBitmapFromStream(InputStream is, InputStream is2, int reqWidth, int reqHeight) {
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeStream(is, null, options);

        options.inSampleSize = calculateInSampleSize(options, reqWidth,
                reqHeight);
        options.inJustDecodeBounds = false;
        //Log.i("Bitmap", "options.inSampleSize: " + options.inSampleSize				+ "\noptions.outWidth:" + options.outWidth				+ " options.outHeight:" + options.outHeight);
        return BitmapFactory.decodeStream(is2, null, options);

    }

    /**
     * 判断网络连接类型，只有在3G或wifi里进行数据发送
     *
     * @param context
     * @return
     */
    public static boolean isNet3g(Context context) {
        ConnectivityManager mConnectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        TelephonyManager mTelephony = (TelephonyManager) context.getSystemService(context.TELEPHONY_SERVICE);
        //检查网络连接，如果无网络可用，就不需要进行连网操作等
        NetworkInfo info = mConnectivity.getActiveNetworkInfo();

        if (info == null || !mConnectivity.getBackgroundDataSetting()) {
            return false;
        }
        int netType = info.getType();
        int netSubtype = info.getSubtype();

        if (netType == ConnectivityManager.TYPE_MOBILE
                && netSubtype == TelephonyManager.NETWORK_TYPE_UMTS
                && !mTelephony.isNetworkRoaming()) {
            return info.isConnected();
        } else {
            return false;
        }
    }

    public static int calculateInSampleSize(BitmapFactory.Options options,
                                            int reqWidth, int reqHeight) {
        // Raw height and width of image
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

        //Log.i("Bitmap", "reqWidth" + reqWidth + "reqHeight" + reqHeight);

        if (height > reqHeight || width > reqWidth) {
            final int heightRatio = Math.round((float) height
                    / (float) reqHeight);
            final int widthRatio = Math.round((float) width / (float) reqWidth);

            //Log.i("Bitmap", "heightRatio" + heightRatio + "widthRatio"					+ widthRatio);

            inSampleSize = heightRatio <= widthRatio ? heightRatio : widthRatio;
            //Log.i("Bitmap", "inSampleSize:" + inSampleSize);
        }
        return inSampleSize;
    }

    public static boolean hasKitKat() {
        return Build.VERSION.SDK_INT >= 19;
    }

    /**
     * Check if OS version has a http URLConnection bug. See here for more
     * information:
     * http://android-developers.blogspot.com/2011/09/androids-http-clients.html
     *
     * @return
     */
    public static boolean hasHttpConnectionBug() {
        return Build.VERSION.SDK_INT < Build.VERSION_CODES.FROYO;
    }

    /**
     * Workaround for bug pre-Froyo, see here for more info:
     * http://android-developers.blogspot.com/2011/09/androids-http-clients.html
     */
    public static void disableConnectionReuseIfNecessary() {
        // HTTP connection reuse which was buggy pre-froyo
        if (hasHttpConnectionBug()) {
            System.setProperty("http.keepAlive", "false");
        }
    }

    /**
     * TODO 获得MD5串
     *
     * @param s
     * @return
     */
    public static String md5(final String s) {
        try {
            MessageDigest digest = MessageDigest.getInstance("MD5");
            digest.update(s.getBytes());
            byte messageDigest[] = digest.digest();

            StringBuffer hexString = new StringBuffer();
            for (int i = 0; i < messageDigest.length; i++) {
                String h = Integer.toHexString(0xFF & messageDigest[i]);
                while (h.length() < 2)
                    h = "0" + h;
                hexString.append(h);
            }
            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
        }
        return "";
    }

    private final static String LINE_SEPARATOR = System.getProperty("line.separator");

    public static String convertStreamToString(InputStream is) {
        /*
		 * To convert the InputStream to String we use the
		 * BufferedReader.readLine() method. We iterate until the BufferedReader
		 * return null which means there's no more data to read. Each line will
		 * appended to a StringBuilder and returned as String.
		 */
        final BufferedReader r = new BufferedReader(new InputStreamReader(is));
        final StringBuilder b = new StringBuilder();
        String line = null;
        try {
            while ((line = r.readLine()) != null) {
                b.append(line);
                b.append(LINE_SEPARATOR);
            }
        } catch (IOException e) {
            return null;
        } finally {
            try {
                is.close();
            } catch (IOException e) {
            }
        }
        return b.toString();
    }

    public static boolean deleteFile(final File file) {
        if (file == null)
            return false;
        if (file.exists()) { // 判断文件是否存在
            if (file.isFile()) { // 判断是否是文件
                return file.delete();
            } else if (file.isDirectory()) { // 否则如果它是一个目录
                File files[] = file.listFiles(); // 声明目录下所有的文件 files[];
                if (files != null) {
                    for (int i = 0; i < files.length; i++) { // 遍历目录下所有的文件
                        if (deleteFile(files[i]) == false) {// 把每个文件用这个方法进行递归
                            return false;
                        }
                    }
                }
            }
            return file.delete();
        }
        return false;
    }

    /**
     * TODO 判断网络状态是否可用
     *
     * @return true: 网络可用 ; false: 网络不可用
     */
    public static boolean hasInternet() {
        ConnectivityManager m = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (m == null) {
            CommLogger.d("NetWorkState", "Unavailabel");
            return false;
        } else {
            NetworkInfo[] info = m.getAllNetworkInfo();
            if (info != null) {
                for (int i = 0; i < info.length; i++) {
                    if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                        CommLogger.d("NetWorkState", "Availabel");
                        return true;
                    }
                }
            }
        }
        return false;
    }

    /**
     * @return 是否是wifi网络
     */
    public static boolean isWifi(Context c) {
        ConnectivityManager m = (ConnectivityManager) c.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo n = m.getActiveNetworkInfo();
        return (n != null && n.getType() == ConnectivityManager.TYPE_WIFI);
    }

    /**
     * Returns 是否有SD卡
     */
    public static boolean hasSDCard() {
        return (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()));
    }

    /**
     * 显示提示框
     */
    public static void showToast(Object msgString) {
        if (msgString == null || msgString.equals(""))
            return;
        Message msg = new Message();
        Bundle data = new Bundle();
        data.putString("ToastMsg", msgString + "");
        msg.what = 0;
        msg.setData(data);
        MsgHandler msgHandler = new MsgHandler(Looper.getMainLooper());
        msgHandler.sendMessage(msg);
    }

    public static void showTips(int stringId) {
        showTips(context.getString(stringId), -1l);
    }

    public static void showTips(String tipsString) {
        showTips(tipsString, -1L);
    }

    public static void showTips(int stringId, long threshold) {
        showTips(context.getString(stringId), threshold);
    }

    /**
     * threshold the downloadtask create time
     */
    public static void showTips(String tipsString, long threshold) {
        Message msg = Message.obtain();
        msg.what = 1;
        Bundle bundle = new Bundle();
        bundle.putString("tipsString", tipsString);
        bundle.putLong("threshold", threshold);
        msg.setData(bundle);
        MsgHandler msgHandler = new MsgHandler(Looper.getMainLooper());
        msgHandler.sendMessage(msg);
    }

    private static class MsgHandler extends Handler {

        public MsgHandler(Looper looper) {
            super(looper);
        }

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    Toast.makeText(context, msg.getData().getString("ToastMsg"), Toast.LENGTH_LONG).show();
                    break;
                case 1:
                    handleShowTipsEvents(msg);
                    break;
            }
            super.handleMessage(msg);
        }

        private long previousToastShow;
        private String previousToastString = "";

        private void handleShowTipsEvents(Message msg) {
            long thisTime = System.currentTimeMillis();
            String thisTimeMsg = msg.getData().getString("tipsString");
            // long threshold = msg.getData().getLong("threshold", -1L);
            String temp = previousToastString;
            previousToastString = thisTimeMsg;
            long tempTime = previousToastShow;
            previousToastShow = thisTime;
            if (thisTimeMsg == null || thisTime - tempTime <= 3500 && thisTimeMsg.equalsIgnoreCase(temp)) {
                previousToastString = temp;
                previousToastShow = tempTime;
                return;
            }
            // Toast t = new Toast(Youku.context);
            // t.setGravity(Gravity.TOP | Gravity.FILL_HORIZONTAL, 0, 0);
            // int duration = msg.getData().getInt("tipsDuration", 0);
            // if (threshold > 0L) {
            // t.setDuration(Toast.LENGTH_SHORT);
            // } else if (duration == 0) {
            // t.setDuration(Toast.LENGTH_LONG);
            // } else {
            // t.setDuration(duration);
            // }
            Toast.makeText(context, msg.getData().getString("tipsString"), Toast.LENGTH_SHORT).show();
            previousToastShow = thisTime;
        }
    }

	/*
	 * ==========================================================================
	 */

    private static SharedPreferences s;

    private static Editor e;

    public static void savePreference(String key, String value) {
        e.putString(key, value).commit();


    }

    public static void savePreference(String key, int value) {
        e.putInt(key, value).commit();
    }

    public static void savePreference(String key, Boolean value) {
        e.putBoolean(key, value).commit();
    }

    public static boolean getPreferenceBoolean(String key) {
        return s.getBoolean(key, false);
    }

    public static boolean isHasKey(String key) {
        return s.contains(key);
    }

    public static String getPreference(String key) {
        if (s == null) {
            return "";
        }
        return s.getString(key, "");
    }

    public static int getPreferenceInt(String key) {
        return s.getInt(key, 0);
    }

    public static boolean getPreferenceBoolean(String key, boolean def) {
        return s.getBoolean(key, def);
    }

    public static String getPreference(String key, String def) {
        return s.getString(key, def);
    }

    public static int getPreferenceInt(String key, int def) {
        return s.getInt(key, def);
    }

	
	/*
	 * ==========================================================================
	 */


    /**
     * 判断网络连接类型，只有在3G或wifi里进行数据发送
     *
     * @param context
     * @return
     */
    public static boolean isNetAvailable(Context context) {
        return checkNet(context);
		/*
			ConnectivityManager mConnectivity = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE); 
			TelephonyManager mTelephony = (TelephonyManager)context.getSystemService(context.TELEPHONY_SERVICE); 
			//检查网络连接，如果无网络可用，就不需要进行连网操作等 
			NetworkInfo info = mConnectivity.getActiveNetworkInfo(); 
	
			if (info == null || !mConnectivity.getBackgroundDataSetting()) { 
				return false; 
			} 
	

			int netType = info.getType(); 
			int netSubtype = info.getSubtype(); 
	
			if (netType == ConnectivityManager.TYPE_WIFI) { 
				return info.isConnected(); 
			} else if (netType == ConnectivityManager.TYPE_MOBILE 
			&& netSubtype == TelephonyManager.NETWORK_TYPE_UMTS 
			&& !mTelephony.isNetworkRoaming()) { 
				return info.isConnected(); 
			} else { 
				return false; 
			} 
			*/
    }

    /*  放入C工程*/

    /* public static String getAppName(Context c) {
         return c.getString(R.string.app_name);
     }
 */
    public static String getAppEnName(Context c) {
        return "";
    }

    public static int getVersionCode(Context c) {
        try {
            PackageInfo ppi = c.getPackageManager().getPackageInfo(c.getPackageName(), 0);
            return ppi.versionCode;
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        return 1;
    }

    public static String getVersionName(Context c) {
        try {
            PackageInfo ppi = c.getPackageManager().getPackageInfo(c.getPackageName(), 0);
            return ppi.versionName;
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        return "1.0";
    }

    public static String getChannelName(Context c, String channelKey) {
        try {
            ApplicationInfo ppi = c.getPackageManager().getApplicationInfo(c.getPackageName(), PackageManager.GET_META_DATA);
            if (ppi.metaData == null) {
                return "360";
            }
            String tmpName = ppi.metaData.getString(channelKey);
            return tmpName;
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        return "360";
    }


    public static boolean checkNet(Context context) {

        try {
            ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            if (connectivity != null) {
                NetworkInfo info = connectivity.getActiveNetworkInfo();
                if (info != null && info.isConnected()) {
                    if (info.getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return false;
    }

    /**
     * 判断网络连接类型，只有在3G或wifi里进行数据发送
     *
     * @param context
     * @return
     */
    public static boolean is3g(Context context) {
        ConnectivityManager mConnectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        TelephonyManager mTelephony = (TelephonyManager) context.getSystemService(context.TELEPHONY_SERVICE);
        //检查网络连接，如果无网络可用，就不需要进行连网操作等
        NetworkInfo info = mConnectivity.getActiveNetworkInfo();

        if (info == null || !mConnectivity.getBackgroundDataSetting()) {
            return false;
        }
        int netType = info.getType();
        int netSubtype = info.getSubtype();

        if (netType == ConnectivityManager.TYPE_MOBILE
                && netSubtype == TelephonyManager.NETWORK_TYPE_UMTS
                && !mTelephony.isNetworkRoaming()) {
            return info.isConnected();
        } else {
            return false;
        }
    }


    public static HttpResponse getResponseFromServerByGet(String urlString) throws IOException {
        // Drawable image = null;
        HttpResponse response = null;
        try {
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpGet request = new HttpGet(urlString);

            try {
                response = (HttpResponse) httpClient.execute(request);
                if (response.getStatusLine().getStatusCode() == 200) {

                    CommLogger.d("http ok:"
                            + response.getStatusLine().getStatusCode());
                    return response;
                } else {
                    CommLogger.d("http error"
                            + response.getStatusLine().getStatusCode());
                }

            } catch (ClientProtocolException e) {
                CommLogger.d(e.toString());
            }
            return response;
            // image = Drawable.createFromStream(is, "");
        } catch (ClientProtocolException e) {
            CommLogger.d(e.toString());
        }
        return response;
    }

    public static long getUrlFileSize(String url) {
        long lenght = 0;
        try {

            //URL mUrl = new URL(urlString);
            URL mUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) mUrl.openConnection();
            conn.setConnectTimeout(5 * 1000);
            conn.setRequestMethod("GET");
            conn.setRequestProperty("Accept-Encoding", "identity");
            conn.setRequestProperty("Referer", url);
            //conn.setRequestProperty("Referer", urlString);
            conn.setRequestProperty("Charset", "UTF-8");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.connect();

            int responseCode = conn.getResponseCode();
            // 判断请求是否成功处理
            if (responseCode == HttpStatus.SC_OK) {
                lenght = conn.getContentLength();
                CommLogger.d("lenght:" + lenght);
            }
        } catch (Exception e1) {
            CommLogger.d(e1.toString());
        }

        return lenght;
    }


    /**
     * GET
     *
     * @param urlString
     * @return
     */
    public static InputStream getDataFromServerByGet(String urlString) throws IOException {
        //Drawable image = null;
        InputStream fileInputStream = null;
        try {
            URL url = new URL(urlString);
            HttpURLConnection httpconn = (HttpURLConnection) url
                    .openConnection();
            //httpconn.setConnectTimeout(CONN_TIMEOUT);
            //httpconn.setReadTimeout(READ_TIMEOUT);
            fileInputStream = httpconn.getInputStream();

            return fileInputStream;
            //image = Drawable.createFromStream(is, "");
        } catch (ClientProtocolException e) {
            CommLogger.d(e.toString());
        }
        return fileInputStream;
    }

    /**
     * 判断当前应用程序处于前台还是后台
     */
    public static boolean isApplicationBroughtToBackground(final Context context) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<RunningTaskInfo> tasks = am.getRunningTasks(1);
        if (!tasks.isEmpty()) {
            ComponentName topActivity = tasks.get(0).topActivity;
            if (!topActivity.getPackageName().equals(context.getPackageName())) {
                return true;
            }
        }
        return false;
    }

    public static boolean isBackground(Context context) {
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
        for (RunningAppProcessInfo appProcess : appProcesses) {
            if (appProcess.processName.equals(context.getPackageName())) {
                if (appProcess.importance == RunningAppProcessInfo.IMPORTANCE_BACKGROUND) {
                    CommLogger.d("后台", appProcess.processName);
                    return true;
                } else {
                    CommLogger.d("前台", appProcess.processName);
                    return false;
                }
            }
        }
        return false;
    }

    public static boolean isRunning(Context context) {
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
        for (RunningAppProcessInfo appProcess : appProcesses) {
            CommLogger.d("(appProcess.processName:" + appProcess.processName);
            if (appProcess.processName.equals(context.getPackageName())) {
                //CommUtils.getPreferenceBoolean(Const.PREF_KEY_IS_EXITED)?false:true
                return true;
            }
        }
        return false;
    }

    public static String getDeviceInfo(Context context) {
        try {
            org.json.JSONObject json = new org.json.JSONObject();
            TelephonyManager tm = (TelephonyManager) context
                    .getSystemService(Context.TELEPHONY_SERVICE);

            String device_id = tm.getDeviceId();

            android.net.wifi.WifiManager wifi = (android.net.wifi.WifiManager) context.getSystemService(Context.WIFI_SERVICE);

            String mac = wifi.getConnectionInfo().getMacAddress();
            json.put("mac", mac);

            if (TextUtils.isEmpty(device_id)) {
                device_id = mac;
            }

            if (TextUtils.isEmpty(device_id)) {
                device_id = android.provider.Settings.Secure.getString(context.getContentResolver(), android.provider.Settings.Secure.ANDROID_ID);
            }

            json.put("device_id", device_id);

            return json.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 防止暴力点击
     *
     * @return
     */
    public synchronized static boolean isFastClick() {
        long time = System.currentTimeMillis();
        if (time - lastClickTime < 1000) {
            return true;
        }
        lastClickTime = time;
        return false;
    }

    /**
     * 获取文件存储目录，如果SD卡不存在，则保存到数据区
     *
     * @return
     */
    public static String getStoragePath() {
        if (hasSDCard()) {
            return Environment.getExternalStorageDirectory().getPath();
        } else {
            return Environment.getDataDirectory().getPath();
        }
    }

    /**
     * 获取可用的SD卡的空间大小
     *
     * @return
     */
    public static long getAvailableExternalMemorySize() {
        if (hasSDCard()) {
            File path = Environment.getExternalStorageDirectory();
            StatFs stat = new StatFs(path.getPath());
            long blockSize = stat.getBlockSize();
            long availableBlocks = stat.getAvailableBlocks();
            return availableBlocks * blockSize;
        } else {
            return 0;
        }
    }

    /**
     * 获取内存大小
     *
     * @return 内部存储空间大小
     */
    public static long getAvailableInternalMemorySize() {
        File path = Environment.getDataDirectory();
        StatFs stat = new StatFs(path.getPath());
        long blockSize = stat.getBlockSize();
        long availableBlocks = stat.getAvailableBlocks();
        return availableBlocks * blockSize;
    }

    /**
     * 判断剩余空间是否足够
     *
     * @param fileSize
     * @return
     */
    public static boolean isLowStorageSpace(long fileSize) {
        long storageSize = 0;
        if (hasSDCard()) {
            storageSize = getAvailableExternalMemorySize();
        } else {
            storageSize = getAvailableInternalMemorySize();
        }
        return storageSize < fileSize;
    }


    public static String getSystemProperty(String propName) {
        String line;
        BufferedReader input = null;
        try {
            Process p = Runtime.getRuntime().exec("getprop " + propName);
            input = new BufferedReader(new InputStreamReader(p.getInputStream()), 1024);
            line = input.readLine();
            input.close();
        } catch (IOException ex) {
            CommLogger.e("Unable to read sysprop " + propName, ex);
            return null;
        } finally {
            if (input != null) {
                try {
                    input.close();
                } catch (IOException e) {
                    CommLogger.e("Exception while closing InputStream", e);
                }
            }
        }
        return line;
    }

    //dp ps px转换相关 dongyanwei 2015-5-8

    /**
     * dp转px
     *
     * @param context
     * @param dpVal
     * @return
     */
    public static int dp2px(Context context, float dpVal) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
                dpVal, context.getResources().getDisplayMetrics());
    }

    /**
     * sp转px
     *
     * @param context
     * @param spVal
     * @return
     */
    public static int sp2px(Context context, float spVal) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,
                spVal, context.getResources().getDisplayMetrics());
    }

    /**
     * px转dp
     *
     * @param context
     * @param pxVal
     * @return
     */
    public static float px2dp(Context context, float pxVal) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (pxVal / scale);
    }

    /**
     * px转sp
     *
     * @param context
     * @param pxVal
     * @return
     */
    public static float px2sp(Context context, float pxVal) {
        return (pxVal / context.getResources().getDisplayMetrics().scaledDensity);
    }


    /**
     * 隐藏软键盘
     */
//    public static void hideSoftKeyBoard(Context context){
//        InputMethodManager imm = (InputMethodManager) context
//                .getSystemService(Context.INPUT_METHOD_SERVICE);
//        if (imm.isActive())  //一直是true
//            imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT,
//                    InputMethodManager.HIDE_NOT_ALWAYS);
//    }

    /**
     * 隐藏软键盘
     */
    public static void hideSoftKeyBoard(Activity activity) {
        View view = activity.getWindow().peekDecorView();
        if (view != null) {
            InputMethodManager inputmanger = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
            inputmanger.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }

    /**
     * 跳转到本应用对应应用市场的详情页
     *
     * @param paramContext
     * @return
     */
    public static Intent getJumpIntent(Context paramContext) {
        StringBuilder localStringBuilder = new StringBuilder().append("market://details?id=");
        String str = paramContext.getPackageName();
        localStringBuilder.append(str);
        Uri localUri = Uri.parse(localStringBuilder.toString());
        return new Intent("android.intent.action.VIEW", localUri).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    }

    /**
     * 判断是否有处理某一个Intent的Activity
     *
     * @param paramContext
     * @param paramIntent
     * @return
     */
    public static boolean judge(Context paramContext, Intent paramIntent) {
        List<ResolveInfo> localList = paramContext.getPackageManager().queryIntentActivities(paramIntent, PackageManager.GET_INTENT_FILTERS);
        if ((localList != null) && (localList.size() > 0)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 判断是否开启GPS
     *
     * @param context
     * @return
     */
    public static boolean isGPSEnable(Context context) {
        String str = Settings.Secure.getString(context.getContentResolver(),
                Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
        if (str != null) {
            return str.contains("gps");
        } else {
            return false;
        }
    }

    /**
     * 开启GPS
     *
     * @return
     */
    public static void setGPSEnable(Context context, boolean bEnabled) {
        if (bEnabled == isGPSEnable(context))
            return;

        Intent gpsIntent = new Intent();
        gpsIntent.setClassName("com.android.settings",
                "com.android.settings.widget.SettingsAppWidgetProvider");
        gpsIntent.addCategory("android.intent.category.ALTERNATIVE");
        gpsIntent.setData(Uri.parse("custom:3"));
        try {
            PendingIntent.getBroadcast(context, 0, gpsIntent, 0).send();
        } catch (PendingIntent.CanceledException e) {
            e.printStackTrace();
        }
    }

    /**
     * 设置GPS
     *
     * @return
     */
    public static void gotoGpsSystemSetting(Activity activity) {
        Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
        activity.startActivityForResult(intent, 0);
    }


}
